package com.movies.filter;

import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by chemeng on 2017/4/5.
 */
public class SecurityFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String old = servletRequest.getScheme() + "://" + servletRequest.getServerName() + ":" + servletRequest.getServerPort() + request.getServletPath();
        filterChain.doFilter(servletRequest, servletResponse);
        SecurityContext securityContext = SecurityContextHolder.getContext();
        if (null != securityContext.getAuthentication() && securityContext.getAuthentication().isAuthenticated()) {
            response.sendRedirect(old);
        }
    }

    public void destroy() {

    }
}
